//
//  FWQQWeiBoHandler.m
//  FWShare
//
//  Created by 范文青 on 14-6-14.
//  Copyright (c) 2014年 fwq. All rights reserved.
//

#import "FWQQWeiBoAuthHandler.h"
#import "FWShare.h"
#import "FWURLQuery.h"
#import "FWAccountProcotol.h"
#import "FWQQWBAuthParam.h"
#import "NSMutableURLRequest+FWHTTPAddition.h"
#import "FWQQWBAccessTokenParam.h"
#import "FWAccessToken.h"
#import "FWQQWBGetUserInfo.h"
#import "FWAuthUser.h"
#import "BBlock.h"

@implementation FWQQWeiBoAuthHandler

- (FWQQWBAccessTokenParam *)accessTokenParam:(NSString *)code
{
    FWQQWBAccessTokenParam *param = [FWQQWBAccessTokenParam new];
    [param setClient_id:[[[FWShare shareCenter] accounts] QQWeiBoAppKey]];
    [param setRedirect_uri:[[[FWShare shareCenter] accounts] QQWeiBoRedirectUrl]];
    [param setCode:code];
    [param setClient_secret:[[[FWShare shareCenter] accounts] QQWeiBoAppSecret]];
    return param;
}
- (FWQQWBAuthParam *)authParam
{
    FWQQWBAuthParam  *param = [FWQQWBAuthParam new];
    [param setClient_id:[[[FWShare shareCenter] accounts] QQWeiBoAppKey]];
    [param setRedirect_uri:[[[FWShare shareCenter] accounts] QQWeiBoRedirectUrl]];
    return param;
}

- (FWQQWBGetUserInfo *)userInfoParam:(FWAccessToken *)token
{
    FWQQWBGetUserInfo *param = [FWQQWBGetUserInfo new];
    [param setOauth_consumer_key:[[[FWShare shareCenter] accounts] QQWeiBoAppKey]];
    [param setAccess_token:[token access_token]];
    [param setOpenid:[token uid]];
    return param;
}

- (void)getUserInfo:(FWAccessToken *)token
{
    FWQQWBGetUserInfo  *userInfo = [self userInfoParam:token];
    NSMutableURLRequest  *request = [NSMutableURLRequest httpRequestWithURL:[NSURL URLWithString:@"http://open.t.qq.com/api/user/info"] parameters:[userInfo dictionaryRepresentation] headers:nil httpMethod:FWHTTPMethodGET contentType:FWPostContentTypeNone];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue new] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        [BBlock dispatchOnMainThread:^{
            NSDictionary  *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            if ([self isValid:dic]) {
                FWAuthUser *user = [FWAuthUser instanceQQWeiBo:dic];
                [user setToken:token];
                [user save];
                if (self.authController.authSuccess) {
                    self.authController.authSuccess(user,self.authController.platform);
                }
            }
        }];
    }];
}
- (void)getAccessToken:(NSString *)code openKey:(NSString *)openKey
{
    NSMutableURLRequest  *request = [NSMutableURLRequest httpRequestWithURL:[NSURL URLWithString:@"https://open.t.qq.com/cgi-bin/oauth2/access_token"] parameters:[[self accessTokenParam:code] dictionaryRepresentation] headers:nil httpMethod:FWHTTPMethodGET contentType:FWPostContentTypeNone];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue new] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        [BBlock dispatchOnMainThread:^{
            NSString  *responseStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            FWURLQuery  *query = [[FWURLQuery alloc] initWithQuery:responseStr];
            NSString  *access_token = [query get:@"access_token"];
            NSString  *expires_in = [query get:@"expires_in"];
            NSString  *openid = [query get:@"openid"];
            FWAccessToken *token = [FWAccessToken instanceQQWeiBo:openid openKey:openKey accessToken:access_token];
            double expires = [expires_in doubleValue] + [[NSDate date] timeIntervalSince1970];
            [token setExpires_in:[NSString stringWithFormat:@"%.0f",expires]];
            [token setRemind_in:expires_in];
            [self getUserInfo:token];
        }];
    }];
}
- (void)startAuth:(FWAuthViewController *)authController
{
    self.authController = authController;
    NSMutableURLRequest *request = [NSMutableURLRequest httpRequestWithURL:[NSURL URLWithString:@"https://open.t.qq.com/cgi-bin/oauth2/authorize"] parameters:[[self authParam] dictionaryRepresentation] headers:nil httpMethod:FWHTTPMethodGET contentType:FWPostContentTypeNone];
    [self.authController.authWebView setDelegate:self];
    [self.authController.authWebView loadRequest:request];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *urlString = [[request URL] description];
    if ([urlString hasPrefix:[[[FWShare shareCenter] accounts] QQWeiBoRedirectUrl]]) {
        FWURLQuery  *query = [[FWURLQuery alloc] initWithURL:[request URL]];
        NSString  *code = [query get:@"code"];
        NSString  *openkey = [query get:@"openkey"];
        [self getAccessToken:code openKey:openkey];
        return NO;
    }
    return YES;
}

- (BOOL)isValid:(NSDictionary *)dic{
    if ([dic objectForKey:@"errcode"] == nil) {
        return YES;
    }
    NSString  *errcode = [[dic objectForKey:@"errcode"] description];
    if ([errcode intValue] == 0) {
        return YES;
    }
    if (self.authController.authFailed) {
        self.authController.authFailed(nil,self.authController.platform);
    }
    return NO;
}
@end
